データから情報を得るときには、大体次のような手順をとります。
問いをもちデータを取得し、視覚化などを通して、データを理解し、さらに問いを深めるサイクルが、データサイエンスの核だと思います。
世界銀行(World Bank)の、世界開発指標(WDI: World Development Indicators)の一つの、GDP(Gross Domestic Product 国内総生産)のデータから始めます。GDP にも何種類かの尺度がありますが、次のものを見てみます。
NY.GDP.MKTP.CD は、データコードと言われるもので、世界開発指標(WDI)には、一つづつ決まっています。
World Development Indicators のサイトの下にある、Data Themes(テーマ)からテーマを選択し、下にスクロールすると、Code をみることができます。ちなみに、ここで利用する NY.GDP.MKTP.CD: GDP (current US$) は、テーマの Economy(経済)の、一番上にあります。
経済用語の英語はよく知らないという方は、ブラウザー(Edge, Google Chrome, Safari など)の翻訳機能を使うのも良いでしょう。ただ、そのページの対話型の機能(interactive function)を利用するときは、翻訳機能をOFF にする必要がある場合もありますので、注意してください。
エラーメッセージを調べるときなどに、英語のほうが情報がたくさん得られますから、言語を、英語に変更しておきます。
R には、WDI のデータを取得する R
のツール(パッケージ)WDI
がありますから、それを使います。また、データを取り扱うための基本的なツール(パッケージ)tidyverse
を使いますので、次のコードで、これらを読み込みます。
Sys.setenv(LANG = "en")
library(tidyverse)
library(WDI)データを取得します。少し時間がかかります。取得したデータに、df_gdp
などと、わかりやすい名前をつけます。df は
data frame の略で、R で標準的なデータの形式です。
df_gdp <- WDI(country = "all",
indicator = c(gdp = "NY.GDP.MKTP.CD"),
extra = TRUE)このコードで、全ての国の GDP を取得できます。GDP
の値は、NY.GDP.MKTP.CD
という名前の列にありますが、覚えやすいように、gdp
という名前に変更しておきます。extra = TRUE
とすることによって、それぞれの国についての情報などが追加されます。
最初の数行だけを見るには、head(df_dgp) とします。
head(df_gdp)データの構造を見るときには、str(df_gdp)
もよく使われます。今度は、列が縦に並んで表示されます。
str(df_gdp)'data.frame': 16758 obs. of 13 variables:
$ country : chr "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
$ iso2c : chr "AF" "AF" "AF" "AF" ...
$ iso3c : chr "AFG" "AFG" "AFG" "AFG" ...
$ year : int 1963 1962 1961 1960 2003 2002 2001 2000 1995 1994 ...
$ gdp : num 7.51e+08 5.47e+08 5.49e+08 5.38e+08 4.54e+09 ...
..- attr(*, "label")= chr "GDP (current US$)"
$ status : chr "" "" "" "" ...
$ lastupdated: chr "2023-05-10" "2023-05-10" "2023-05-10" "2023-05-10" ...
$ region : chr "South Asia" "South Asia" "South Asia" "South Asia" ...
$ capital : chr "Kabul" "Kabul" "Kabul" "Kabul" ...
$ longitude : chr "69.1761" "69.1761" "69.1761" "69.1761" ...
$ latitude : chr "34.5228" "34.5228" "34.5228" "34.5228" ...
$ income : chr "Low income" "Low income" "Low income" "Low income" ...
$ lending : chr "IDA" "IDA" "IDA" "IDA" ...
概要 (summary(df_gdp)) からもある程度わかります。
summary(df_gdp) country iso2c iso3c
Length:16758 Length:16758 Length:16758
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
year gdp status
Min. :1960 Min. :8.824e+06 Length:16758
1st Qu.:1975 1st Qu.:2.442e+09 Class :character
Median :1991 Median :1.784e+10 Mode :character
Mean :1991 Mean :1.161e+12
3rd Qu.:2007 3rd Qu.:2.156e+11
Max. :2022 Max. :9.653e+13
NA's :3602
lastupdated region capital
Length:16758 Length:16758 Length:16758
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
longitude latitude income
Length:16758 Length:16758 Length:16758
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
lending
Length:16758
Class :character
Mode :character
国のリストをみてみましょう。とても長いリストの中には、地域名も含まれています。
df_gdp %>% distinct(country) %>% pull() [1] "Afghanistan"
[2] "Africa Eastern and Southern"
[3] "Africa Western and Central"
[4] "Albania"
[5] "Algeria"
[6] "American Samoa"
[7] "Andorra"
[8] "Angola"
[9] "Antigua and Barbuda"
[10] "Arab World"
[11] "Argentina"
[12] "Armenia"
[13] "Aruba"
[14] "Australia"
[15] "Austria"
[16] "Azerbaijan"
[17] "Bahamas, The"
[18] "Bahrain"
[19] "Bangladesh"
[20] "Barbados"
[21] "Belarus"
[22] "Belgium"
[23] "Belize"
[24] "Benin"
[25] "Bermuda"
[26] "Bhutan"
[27] "Bolivia"
[28] "Bosnia and Herzegovina"
[29] "Botswana"
[30] "Brazil"
[31] "British Virgin Islands"
[32] "Brunei Darussalam"
[33] "Bulgaria"
[34] "Burkina Faso"
[35] "Burundi"
[36] "Cabo Verde"
[37] "Cambodia"
[38] "Cameroon"
[39] "Canada"
[40] "Caribbean small states"
[41] "Cayman Islands"
[42] "Central African Republic"
[43] "Central Europe and the Baltics"
[44] "Chad"
[45] "Channel Islands"
[46] "Chile"
[47] "China"
[48] "Colombia"
[49] "Comoros"
[50] "Congo, Dem. Rep."
[51] "Congo, Rep."
[52] "Costa Rica"
[53] "Cote d'Ivoire"
[54] "Croatia"
[55] "Cuba"
[56] "Curacao"
[57] "Cyprus"
[58] "Czechia"
[59] "Denmark"
[60] "Djibouti"
[61] "Dominica"
[62] "Dominican Republic"
[63] "Early-demographic dividend"
[64] "East Asia & Pacific"
[65] "East Asia & Pacific (excluding high income)"
[66] "East Asia & Pacific (IDA & IBRD countries)"
[67] "Ecuador"
[68] "Egypt, Arab Rep."
[69] "El Salvador"
[70] "Equatorial Guinea"
[71] "Eritrea"
[72] "Estonia"
[73] "Eswatini"
[74] "Ethiopia"
[75] "Euro area"
[76] "Europe & Central Asia"
[77] "Europe & Central Asia (excluding high income)"
[78] "Europe & Central Asia (IDA & IBRD countries)"
[79] "European Union"
[80] "Faroe Islands"
[81] "Fiji"
[82] "Finland"
[83] "Fragile and conflict affected situations"
[84] "France"
[85] "French Polynesia"
[86] "Gabon"
[87] "Gambia, The"
[88] "Georgia"
[89] "Germany"
[90] "Ghana"
[91] "Gibraltar"
[92] "Greece"
[93] "Greenland"
[94] "Grenada"
[95] "Guam"
[96] "Guatemala"
[97] "Guinea"
[98] "Guinea-Bissau"
[99] "Guyana"
[100] "Haiti"
[101] "Heavily indebted poor countries (HIPC)"
[102] "High income"
[103] "Honduras"
[104] "Hong Kong SAR, China"
[105] "Hungary"
[106] "IBRD only"
[107] "Iceland"
[108] "IDA & IBRD total"
[109] "IDA blend"
[110] "IDA only"
[111] "IDA total"
[112] "India"
[113] "Indonesia"
[114] "Iran, Islamic Rep."
[115] "Iraq"
[116] "Ireland"
[117] "Isle of Man"
[118] "Israel"
[119] "Italy"
[120] "Jamaica"
[121] "Japan"
[122] "Jordan"
[123] "Kazakhstan"
[124] "Kenya"
[125] "Kiribati"
[126] "Korea, Dem. People's Rep."
[127] "Korea, Rep."
[128] "Kosovo"
[129] "Kuwait"
[130] "Kyrgyz Republic"
[131] "Lao PDR"
[132] "Late-demographic dividend"
[133] "Latin America & Caribbean"
[134] "Latin America & Caribbean (excluding high income)"
[135] "Latin America & the Caribbean (IDA & IBRD countries)"
[136] "Latvia"
[137] "Least developed countries: UN classification"
[138] "Lebanon"
[139] "Lesotho"
[140] "Liberia"
[141] "Libya"
[142] "Liechtenstein"
[143] "Lithuania"
[144] "Low & middle income"
[145] "Low income"
[146] "Lower middle income"
[147] "Luxembourg"
[148] "Macao SAR, China"
[149] "Madagascar"
[150] "Malawi"
[151] "Malaysia"
[152] "Maldives"
[153] "Mali"
[154] "Malta"
[155] "Marshall Islands"
[156] "Mauritania"
[157] "Mauritius"
[158] "Mexico"
[159] "Micronesia, Fed. Sts."
[160] "Middle East & North Africa"
[161] "Middle East & North Africa (excluding high income)"
[162] "Middle East & North Africa (IDA & IBRD countries)"
[163] "Middle income"
[164] "Moldova"
[165] "Monaco"
[166] "Mongolia"
[167] "Montenegro"
[168] "Morocco"
[169] "Mozambique"
[170] "Myanmar"
[171] "Namibia"
[172] "Nauru"
[173] "Nepal"
[174] "Netherlands"
[175] "New Caledonia"
[176] "New Zealand"
[177] "Nicaragua"
[178] "Niger"
[179] "Nigeria"
[180] "North America"
[181] "North Macedonia"
[182] "Northern Mariana Islands"
[183] "Norway"
[184] "Not classified"
[185] "OECD members"
[186] "Oman"
[187] "Other small states"
[188] "Pacific island small states"
[189] "Pakistan"
[190] "Palau"
[191] "Panama"
[192] "Papua New Guinea"
[193] "Paraguay"
[194] "Peru"
[195] "Philippines"
[196] "Poland"
[197] "Portugal"
[198] "Post-demographic dividend"
[199] "Pre-demographic dividend"
[200] "Puerto Rico"
[201] "Qatar"
[202] "Romania"
[203] "Russian Federation"
[204] "Rwanda"
[205] "Samoa"
[206] "San Marino"
[207] "Sao Tome and Principe"
[208] "Saudi Arabia"
[209] "Senegal"
[210] "Serbia"
[211] "Seychelles"
[212] "Sierra Leone"
[213] "Singapore"
[214] "Sint Maarten (Dutch part)"
[215] "Slovak Republic"
[216] "Slovenia"
[217] "Small states"
[218] "Solomon Islands"
[219] "Somalia"
[220] "South Africa"
[221] "South Asia"
[222] "South Asia (IDA & IBRD)"
[223] "South Sudan"
[224] "Spain"
[225] "Sri Lanka"
[226] "St. Kitts and Nevis"
[227] "St. Lucia"
[228] "St. Martin (French part)"
[229] "St. Vincent and the Grenadines"
[230] "Sub-Saharan Africa"
[231] "Sub-Saharan Africa (excluding high income)"
[232] "Sub-Saharan Africa (IDA & IBRD countries)"
[233] "Sudan"
[234] "Suriname"
[235] "Sweden"
[236] "Switzerland"
[237] "Syrian Arab Republic"
[238] "Tajikistan"
[239] "Tanzania"
[240] "Thailand"
[241] "Timor-Leste"
[242] "Togo"
[243] "Tonga"
[244] "Trinidad and Tobago"
[245] "Tunisia"
[246] "Turkiye"
[247] "Turkmenistan"
[248] "Turks and Caicos Islands"
[249] "Tuvalu"
[250] "Uganda"
[251] "Ukraine"
[252] "United Arab Emirates"
[253] "United Kingdom"
[254] "United States"
[255] "Upper middle income"
[256] "Uruguay"
[257] "Uzbekistan"
[258] "Vanuatu"
[259] "Venezuela, RB"
[260] "Vietnam"
[261] "Virgin Islands (U.S.)"
[262] "West Bank and Gaza"
[263] "World"
[264] "Yemen, Rep."
[265] "Zambia"
[266] "Zimbabwe"
今回は下のように、%>%(パイプと呼びます)
で繋げてコードを書きました。
df_gdp %>% distinct(country) %>% pull()
最初は、データ、その中の、異なる国を選択して、書き出してくださいというものです。
これは、
pull(distinct(df_gdp, country))
と同じです。どんどん、かっこの中に入れ子になって複雑になるので、一つ一つのステップを、順に書いたものが、最初のものになります。
df_gdp %>% head()
df_gdp %>% str()
なども可能です。かっこの中に最初に入るものが直前のもの、ここでは、データになっています。
変数が多いので、日本の部分だけ filter
を使って選択します。country が Japan
と一致する場合のみを選択するときは、==
を使います。数値ではないので、引用符をつけます。半角を使ってください。
df_gdp %>% filter(country == "Japan")df_gdp %>% filter(country == "Japan") %>% head(2)2行目の、gdp の、4.940878e+12 は、Scientific notation
と言われるもので、 \[4.940878 \times 10^{12}
= 4,940,887,800,000\] を意味します。e+3
は千(thousand)、e+6 は百万(million)、e+9
は、10億(billion)、e+12
は、兆(trillion)ですから、日本の、2021 年の GDP
は、約5兆ドルとなります。
df_gdp %>% filter(country == "Japan") %>%
ggplot(aes(x = year, y = gdp)) + geom_line()df_gdp %>% filter(country == "Japan") %>%
ggplot(aes(x = year, y = gdp)) + geom_line()
日本を選択したときに、それに名前をつけておいて、それを使うこともできますが、名前がどんどん増えるので、それに続けて、コードを書いていく方法をとっています。
ggplot(aes(x = year, y = gdp)) + geom_line()
の部分が、グラフを描く部分で、「x 軸を、year、y 軸を、gdp として、それを、折線グラフで描いてください」というコードです。
Warning: [38;5;238mRemoved 1 row containing missing values
と表示されています。値がない年があることを言っています。2022年のデータがないことがわかっていますから、最初から削除してこくことも可能です。
視覚化によって見えてくることがいくつもありますね。どんなことがわかりますか。気づいたこと(observation)をあげてみましょう。
コードを描くことではなく、この部分が、データサイエンスの核の部分です。気づいたことを列挙してみましょう。
summary(df_gdp)
で、データ自体は、1960年から2022年までのようですが、日本も、2022年のデータはありませんでしたから、年によって、どの程度データがあるか、調べてみます。
df_gdp %>% drop_na(gdp) %>% ggplot(aes(x = year)) + geom_bar()df_gdp %>% drop_na(gdp) %>% ggplot(aes(x = year)) + geom_bar()
バー・グラフを使いますが、gdp の値が、欠損値(NA: not
available)のデータを削除してから、グラフを描きます。
最新の2021年のデータはすべてあるわけではなさそうですが、gdp
の値が大きい順に並べてみましょう。
df_gdp %>% filter(year == 2021) %>% drop_na(gdp) %>% arrange(desc(gdp))最初に、World
と表示され、グループや、カテゴリーのデータもあるようですから、それを、まず、削除することが必要です。region
の列を見ると、World などは、Aggregates
となっているので、そのようなものを削除すればよさそうです。数値の大きい順に並べたいので、desc
降順(descending order)にします。
df_gdp %>% filter(year == 2021, region != "Aggregates") %>%
drop_na(gdp) %>% arrange(desc(gdp))これは、グラフではありませんが、これも一つの視覚化とも考えられないことはありません。
上位7カ国は、United States, China, Japan, Germany, India, United Kingdom, France であることがわかりました。8番目は、Italy でここまでが、GDP が 2兆ドルを越している国となります。
df_gdp %>% filter(iso2c %in% c("US", "CN", "JP", "DE", "IN", "GB", "FR")) %>%
ggplot(aes(x = year, y = gdp, col = iso2c)) + geom_line()df_gdp %>% filter(iso2c %in% c("US", "CN", "JP", "DE", "IN", "GB", "FR")) %>%
ggplot(aes(x = year, y = gdp, col = iso2c)) + geom_line()
ここでは、最初に、filter
を使って、7カ国のデータを選択しています。
そのときには、%in% として、国名を、combine
するといういみで、c()
とひとまとめにします。数字ではなく、文字なので、引用符で囲んでいます。この場合は、single
quote でも構いませんが、半角を使ってください。
このグラフからは、どのようなことがわかりますか。気づいたことを書いてみましょう。
もう少し、このようなグラフをみてみたいというような、メモも大切です。
df_gdp %>%
filter(region != "Aggregates") %>% drop_na(gdp) %>%
group_by(year) %>% mutate(gdp_ratio = gdp/sum(gdp)) %>% ungroup() %>%
filter(iso2c %in% c("US", "CN", "JP", "DE", "IN", "GB", "FR")) %>%
ggplot(aes(x = year, y = gdp_ratio, fill = iso2c)) + geom_area() +
geom_line(col = "black", position = "stack", linewidth = 0.3) +
scale_y_continuous(labels = scales::percent_format(accuracy = 1))まず、下の部分が新しいですが、ここでは、年毎にグループにして、その上で、新しい
dgp_ratio という名前の列を追加し、その gdp の値を、gdp
合計で割っています。すなわち、世界の、GDP
における割合が計算されています。
group_by(year) %>% mutate(gdp_ratio = gdp/sum(gdp)) %>% ungroup() %>%
下の部分では、geom_area
を使って、fill=iso2c により、iso2c
ごとに、違う色を塗って、position = “stack”
により、積み上げ型の、グラフを描き、境目がわかりやすいように、0.3
の太さの黒の線を描いてください。また、y
軸は、小数点以下を省いたパーセント表示に変えてください。というコードです。
ggplot(aes(x = year, y = gdp_ratio, fill = iso2c)) + geom_area() +
geom_line(col = "black", position = "stack", linewidth = 0.3) +
scale_y_continuous(labels = scales::percent_format(accuracy = 1))
これは、上から、iso2c の アルファベットの順番になっていますが、積み上げの順序を変更することもできます。
df_gdp %>%
filter(region != "Aggregates") %>% drop_na(gdp) %>%
group_by(year) %>% mutate(gdp_ratio = gdp/sum(gdp)) %>% ungroup() %>%
filter(iso2c %in% c("US", "CN", "JP", "DE", "IN", "GB", "FR")) %>%
mutate(iso2co = factor(iso2c, levels = c("IN", "CN", "FR", "GB", "DE", "JP", "US"))) %>%
ggplot(aes(x = year, y = gdp_ratio, fill = iso2co)) + geom_area() +
geom_line(col = "black", position = "stack", linewidth = 0.3) +
scale_y_continuous(labels = scales::percent_format(accuracy = 1))これらは、世界全体の GPT における割合です。
どのようなことがわかりますか。
主要国で、60%〜70% を占めていることがわかります。それぞれの国や、幾つかの国の影響力も、ある程度みることができるように見えます。
気づいたこと、疑問に思ったことなどを、書き出してみてください。
GDP が大きな国と、小さな国があるのはわかりますが、それは、どのように分布しているのでしょうか。
df_gdp %>% drop_na(gdp) %>%
filter(year == 2021) %>%
ggplot(aes(gdp)) + geom_histogram()小さいところに集中していることがわかりますが、scale_x_log10()
を加え、対数軸をとってみます。
\(log10(1000) = 3\), \(log10(1000000) = 6\), \(log10(1000000000) = 9\) などになります。
df_gdp %>% drop_na(gdp) %>%
filter(year == 2021) %>%
ggplot(aes(gdp)) + geom_histogram() + scale_x_log10()幅を変更したり、分ける個数を変更するには binwidth = 0.5
や、bins = 20 を、geom_histogram()
のかっこの中に入れます。
また、密度曲線に変えるには、geom_density
を使います。
df_gdp %>% drop_na(gdp) %>%
filter(year == 2021) %>%
ggplot(aes(gdp)) + geom_density() + scale_x_log10()これは、2021年のデータですが、density の変化を見てみます。alpha の値は透明度です。
df_gdp %>% drop_na(gdp) %>%
filter(year %in% c(1961, 1971, 1981, 1991, 2001, 2011, 2021)) %>%
ggplot(aes(gdp, fill = factor(year))) + geom_density(alpha = 0.4) + scale_x_log10()少しみにくいので、分けてみます。
df_gdp %>% drop_na(gdp) %>%
filter(year %in% c(1971, 1981, 1991, 2001, 2011, 2021)) %>%
ggplot(aes(gdp, fill = factor(year))) +
geom_density() + scale_x_log10() + facet_wrap(~year)いくつかのグループごとに分布をみてみることも可能です。それには、Boxplot が有効です。
df_gdp %>% drop_na(gdp) %>% filter(region != "Aggregates") %>%
drop_na(region) %>% filter(year %in% c(2021)) %>%
ggplot(aes(gdp, region, fill = region)) +
geom_boxplot() + scale_x_log10() + labs(y = "") +
theme(legend.position = "none")df_gdp %>% drop_na(gdp) %>% filter(region != "Aggregates") %>%
drop_na(income) %>% filter(year %in% c(2021)) %>%
mutate(level = factor(income, c("High income", "Upper middle income", "Lower middle income", "Low income"))) %>%
ggplot(aes(gdp, level, fill = income)) +
geom_boxplot() + scale_x_log10() + labs(y = "") +
theme(legend.position = "none")これからも、いろいろなことがわかりますね。
地図で、国の income level をみてみましょう。
library(maps)
map_world <- map_data('world')
map_gdp <- map_world %>%
mutate(iso2c = iso.alpha(region, n=2)) %>%
mutate(map_region = region) %>% select(-region) %>%
left_join(df_gdp, by = "iso2c") Warning: Detected an unexpected many-to-many relationship between `x` and `y`.
head(map_gdp)map_gdp %>% mutate(income_level = factor(income, levels = c("High income", "Upper middle income", "Lower middle income", "Low income", "Not classified", NA))) %>%
ggplot() +
geom_map(aes(long, lat, map_id = map_region, fill = income_level), map = map_world, col = "black", size = 0.1) Warning: Ignoring unknown aesthetics: x and y
map_gdp %>% mutate(income_level = factor(income, levels = c("High income", "Upper middle income", "Lower middle income", "Low income", "Not classified", NA))) %>%
filter(year == 2021) %>%
ggplot() +
geom_map(aes(x=long, y=lat, map_id = map_region, fill = gdp), map = map_world, col = "black", size = 0.1) Warning: Ignoring unknown aesthetics: x and y
今回は、経済指標である、GDP を使いました。データサイエンスについて少しずつ、学んでいきます。
コードの説明は、簡単にしかしていませんから、理解するのは難しいと思いますが、いくつかのことは、ご理解いただけると思います。
それほど、長くはない、コードで、データを見ていく。R は対話型(interactive)のプログラミング言語と言われています。
コードに続けて、結果が表示されるので、コードと出力の対応が見やすい。また、コメントや説明も併記することができる。これは、RMarkdown という形式の中で、コードを書いていることによるものです。RMarkdown は、再現性(reproducibility)と、プログラム・コードの内容をコンピュータにわかるようにでなく、人間にもわかるように記述する(Literate Programming)を実現しています。
視覚化(Visualization)によって、わかることが色々とある。また、視覚化の方法もたくさんあり、いろいろな見方をすることで、データについての理解が深まっていく。
視覚化を通して、データを理解すること、問いを持ち、他の視覚化などを用いて、さらに、理解を深めることがたいせつ。
理解したことを元にして、さらに、そのデータ、または、他のデータを使って、新たな発見をしていく。
統計的な指標も用いますが、それらによって、新しい知識を生み出すとも表現しますが、そのような営み全体が、データサイエンスの核をなす部分だと思います。
オープンデータという言葉は、厳密な意味を持っています。データまたはコンテンツは、出所が明示されオープンという性質が維持されれば、誰でも自由に利用、再利用、再配布できるものを言います。
データは法的にオープンでなければなりません。つまり、パブリックドメインに置かれ、最小限の制限で自由に使用できなければなりません。
データは技術的にオープンでなければなりません。つまり、誰でも自由に使える一般的なソフトウェアツールを使ってデータにアクセスし、機械で読み取ることが可読な電子フォーマットで提供されていなければならなりません。パスワードやファイアウォールによる制限を受けずに、公共のサーバーで、だれでもアクセスできなければなりません。また、オープンデータを見つけやすくするために、さまざまな組織がオープンデータカタログを作成し管理してく必要があります。
https://datatopics.worldbank.org/world-development-indicators/
以下では、世界銀行の、世界開発指標を利用する。
他にも、活用できるサイトがいくつかある。
なども、同様の、ダッシュボードを備えており、データの提供もしている。
日本では、
WDI
パッケージで、データをダウンロードしたり、探したり、詳細情報を得たりできます。
検索や、ダウンロード方法が理解できるように、例示してありますが、ざっと確認して、4.3.3 のテンプレートを利用すると、グラフを描くこともできます。
WDIsearch(string = "gdp", field = "name", short = TRUE, cache = NULL)WDIsearch(string = "military expenditure", field = "name", short = TRUE, cache = NULL)WDIsearch(string = "NY.GDP.MKTP.CD", field = "indicator", short = TRUE, cache = NULL)名前で検索(“” の間に、(なるべく簡単な)検索文字列を入れてください。)
WDIsearch(string = "", field = "name", short = TRUE, cache = NULL)Indicator で検索(“” の間に、調べたい indicator を入れてください。)
WDIsearch(string = "", field = "indicator", short = TRUE, cache = NULL)short = FALSE
とします。時間がかかるので、検索は、Indicator
と、名前などの情報をもったファイルを手元に持っておくことにします。
wdi_cache <- WDIcache()右上の窓枠(pane)から、wdi_cache
を探して、中身を見てみましょう。series と、country
の二つのデータ・フレームからなっているリストです。三角印や、右から二番目の巻物のようなアイコンをクリックすると中身が見えます。
WDIsearch(string = "CPI Price", field = "name", short = FALSE, cache = wdi_cache)WDIsearch(string = "NY.GDP.MKTP.KD.ZG", field = "indicator", short = FALSE, cache = wdi_cache)string と、field
を、ふたつとも入れてください。
WDIsearch(string = "", field = "", short = FALSE, cache = wdi_cache)Indicator が決まったら、ダウンロードします。
右下の、Help Tab に WDI と入れると、使い方もわかります。
?WDIdf_gdp1 <- WDI(country = "all", indicator = "NY.GDP.MKTP.CD")
df_gdp1df_gdp2 <- WDI(country = "all", indicator = c(gdp = "NY.GDP.MKTP.CD"))
df_gdp2df_gdp3 <- WDI(country = "all", indicator = c(gdp = "NY.GDP.MKTP.CD"), extra=TRUE, cache=wdi_cache)
df_gdp3df_gdp4 <- WDI(country = c("CN","GB","JP","IN","US","DE"), indicator = c(gdp = "NY.GDP.MKTP.CD"), extra=TRUE, cache=wdi_cache)
df_gdp4df_gdp21 <- WDI(country = "all",
indicator = c(gdp_deflator = "NY.GDP.DEFL.KD.ZG",
cpi_price = "CPTOTNSXN"),
extra=TRUE, cache=wdi_cache)
df_gdp21str(df_gdp21)'data.frame': 24238 obs. of 14 variables:
$ country : chr "Advanced Economies" "Advanced Economies" "Advanced Economies" "Advanced Economies" ...
$ iso2c : chr "AME" "AME" "AME" "AME" ...
$ iso3c : chr "" "" "" "" ...
$ year : int 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 ...
$ status : chr "" "" "" "" ...
$ lastupdated : chr "2020-07-27" "2020-07-27" "2020-07-27" "2020-07-27" ...
$ gdp_deflator: num NA NA NA NA NA NA NA NA NA NA ...
..- attr(*, "label")= chr "Inflation, GDP deflator (annual %)"
$ cpi_price : num 58.7 60.5 63 66 69.1 ...
..- attr(*, "label")= chr "CPI Price,not seas.adj,,,"
$ region : chr NA NA NA NA ...
$ capital : chr NA NA NA NA ...
$ longitude : chr NA NA NA NA ...
$ latitude : chr NA NA NA NA ...
$ income : chr NA NA NA NA ...
$ lending : chr NA NA NA NA ...
summary(df_gdp21) country iso2c iso3c
Length:24238 Length:24238 Length:24238
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
year status lastupdated
Min. :1960 Length:24238 Length:24238
1st Qu.:1982 Class :character Class :character
Median :1997 Mode :character Mode :character
Mean :1995
3rd Qu.:2009
Max. :2022
gdp_deflator cpi_price region
Min. : -98.704 Min. : 0.00 Length:24238
1st Qu.: 2.315 1st Qu.: 55.95 Class :character
Median : 5.256 Median : 83.28 Mode :character
Mean : 25.299 Mean : 84.18
3rd Qu.: 10.386 3rd Qu.:108.75
Max. :26765.858 Max. :551.25
NA's :11881 NA's :18676
capital longitude latitude
Length:24238 Length:24238 Length:24238
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
income lending
Length:24238 Length:24238
Class :character Class :character
Mode :character Mode :character
右上の窓枠の、Environment も見てみましょう。
グラフ(Chart)を描いて視覚化しよう
df_gdp4 %>% ggplot(aes(year, gdp, col=country)) + geom_line()df_gdp4 %>% drop_na(gdp) %>%
ggplot(aes(year, gdp, col=country)) + geom_line() +
labs(title = paste("WDI - NY.GDP.MKTP.CD: ", "gdp"))Line Plot with one indicator with abbreviation and one country
chosen_indicator <- "SL.UEM.TOTL.NE.ZS"
short_name <- "unemployment"
chosen_country <- "United States"
WDI(country = "all", indicator = c(short_name = chosen_indicator), extra=TRUE, cache=wdi_cache) %>%
filter(country == chosen_country) %>%
ggplot(aes(year, short_name)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator, ": ", short_name, " - ", chosen_country),
y = short_name)Line Plot with one indicator and one country
chosen_indicator <- "SL.UEM.TOTL.NE.ZS"
chosen_country <- "United States"
WDI(country = "all", indicator = c(chosen_indicator = chosen_indicator),
extra=TRUE, cache=wdi_cache) %>%
filter(country == chosen_country) %>%
ggplot(aes(year, chosen_indicator)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator, " - ", chosen_country),
y = chosen_indicator)Line Plot with one indicator with abbreviation and several countries
chosen_indicator <- "SL.UEM.TOTL.NE.ZS"
short_name <- "unemployment"
chosen_countries <- c("United States","United Kingdom", "Japan")
WDI(country = "all", indicator = c(short_name = chosen_indicator), extra=TRUE, cache=wdi_cache) %>% drop_na(short_name) %>%
filter(country %in% chosen_countries) %>%
ggplot(aes(year, short_name, col = country)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator, ": ", short_name), y = short_name)Line Plot with two indicators with abbreviation and one country
chosen_indicator_1 <- "NY.GDP.DEFL.KD.ZG"
short_name_1 <- "gdp_deflator"
chosen_indicator_2 <- "CPTOTSAXNZGY"
short_name_2 <- "cpi_price"
chosen_country <- "United States"
WDI(country = "all", indicator = c(short_name_1 = chosen_indicator_1, short_name_2 = chosen_indicator_2), extra=TRUE, cache=wdi_cache) %>%
filter(country == chosen_country) %>%
pivot_longer(c(short_name_1, short_name_2), names_to = "class", values_to = "value") %>% drop_na(value) %>%
ggplot(aes(year, value, col = class)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator_1, ": ", short_name_1, "\n", chosen_indicator_2, ": ", short_name_2, " - ", chosen_country)) +
scale_color_manual(labels = c(short_name_1, short_name_2), values = scales::hue_pal()(2))chosen_indicator_1 <- "SL.TLF.CACT.MA.NE.ZS"
short_name_1 <- "male"
chosen_indicator_2 <- "SL.TLF.CACT.FE.NE.ZS"
short_name_2 <- "female"
chosen_country <- "United States"
WDI(country = "all", indicator = c(short_name_1 = chosen_indicator_1, short_name_2 = chosen_indicator_2), extra=TRUE, cache=wdi_cache) %>%
filter(country == chosen_country) %>%
pivot_longer(c(short_name_1, short_name_2), names_to = "class", values_to = "value") %>% drop_na(value) %>%
ggplot(aes(year, value, col = class)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator_1, ": ", short_name_1, "\n", chosen_indicator_2, ": ", short_name_2, " - ", chosen_country)) +
scale_color_manual(labels = c(short_name_1, short_name_2), values = scales::hue_pal()(2))Line Plot with two indicators with abbreviation and several countries
chosen_indicator_1 <- "NY.GDP.DEFL.KD.ZG"
short_name_1 <- "gdp_deflator"
chosen_indicator_2 <- "CPTOTSAXNZGY"
short_name_2 <- "cpi_price"
chosen_countries <- c("United States", "France", "Japan")
WDI(country = "all", indicator = c(short_name_1 = chosen_indicator_1, short_name_2 = chosen_indicator_2), extra=TRUE, cache=wdi_cache) %>%
filter(country %in% chosen_countries) %>%
pivot_longer(c(short_name_1, short_name_2), names_to = "class", values_to = "value") %>% drop_na(value) %>%
ggplot(aes(year, value, linetype = class, col = country)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator_1, ": ", short_name_1, "\n", chosen_indicator_2, ": ", short_name_2)) +
scale_linetype_manual(labels = c(short_name_1, short_name_2), values = c("solid", "dashed"))chosen_indicator_1 <- "SL.TLF.CACT.MA.NE.ZS"
short_name_1 <- "male"
chosen_indicator_2 <- "SL.TLF.CACT.FE.NE.ZS"
short_name_2 <- "female"
chosen_countries <- c("United States", "France", "Japan")
WDI(country = "all", indicator = c(short_name_1 = chosen_indicator_1, short_name_2 = chosen_indicator_2), extra=TRUE, cache=wdi_cache) %>%
filter(country %in% chosen_countries) %>%
pivot_longer(c(short_name_1, short_name_2), names_to = "class", values_to = "value") %>% drop_na(value) %>%
ggplot(aes(year, value, linetype = class, col = country)) + geom_line() +
labs(title = paste("WDI ", chosen_indicator_1, ": ", short_name_1, "\n", chosen_indicator_2, ": ", short_name_2)) +
scale_linetype_manual(labels = c(short_name_1, short_name_2), values = c("solid", "dashed"))上のテンプレートをコピーして、下に貼り付け、指標
indicator と、略称 short_name
と、いくつかの国名 chosen_countries
を、入れ替えて、試してみてください。
19人の受講生に、興味のある指標を選んで、テンプレートを使って、可視化をしてみてください、と課題に出した時に、調べてくれたものです。
url_indicators <- "https://ds-sl.github.io/intro2r/data/indicators.csv"
df_indicators <- read_csv(url_indicators) %>% left_join(wdi_cache$series)Rows: 89 Columns: 5── Column specification ───────────────────────────────────────────
Delimiter: ","
chr (5): indicator, name, description, sourceDatabase, sourceOr...
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.Joining with `by = join_by(indicator, name, description, sourceDatabase, sourceOrganization)`
write_csv(df_indicators, "./data/indicators.csv")
df_indicators %>% distinct(indicator, name) %>% arrange(indicator)自分で課題を考え、データを選べることは、とても大切だということだと思います。
EDAは、データが何を語っているかを理解するための反復的なサイクルです。
まず、データに関する問いを作成します。
データの可視化、変換、モデリングを行い、答えを探します。
学習したことを活用して、問いを修正したり、新しい問いを考えたりします。そして、このサイクルを繰り返していきます。
EDAはデータ分析において重要な役割を果たします。また、データの品質を保証するために、データの質を確認するために使用することもできます。
R4DS からのイメージ
問いをもちデータを取得し、視覚化などを通して、データを理解し、さらに問いを深めるサイクルが、データサイエンスの核ではないかと思います。
スタートは、本来は、データの作成・探索ですが、すでに、分析したいデータはすでにあるとして話を進めます。まずは、data
フォルダ(directory)を作成しておくと良い。右下の窓枠の Files
タブから、New Folder で作成してもよい。
dir.create("./data")データの取得・読み込みを、四つの方法に分けて説明します。
write(df_name, "./data/name.csv")df_name <- read_csv("./data/file_name.csv")df_name <- read_csv(url_of_a_csv)library(readxl)。df_name <- read_excel("./data/file_name.xlsx")df_name <- read_delim(clipboard())WDIcache() の扱い二つの、ファイルが一つになった、リストであるため、違って命令を使います。
wdi_cache <- WDIcache()
write_rds(wdi_cache, "./data/wdi_cache.RData")wdi_cache <- read_rds("./data/wdi_cache.RData")df_military6 <- WDI(country = c("CN","GB","JP","IN","US","DE"), indicator = c(military = "MS.MIL.XPND.CD"), extra=TRUE, cache=wdi_cache)
df_military6 %>% filter(year == 2021) %>% arrange(desc(military))df_military6 %>% drop_na(military) %>%
ggplot(aes(year, military, col=iso2c)) + geom_line()df_military <- WDI(country = "all", indicator = c(military = "MS.MIL.XPND.CD"), extra=TRUE, cache=wdi_cache)df_military %>% drop_na(military) %>% filter(year==2021, income=="High income", military >0) %>%
ggplot(aes(military, fill=region)) + geom_density() + geom_vline(xintercept = 54123551702, col="red") + scale_x_log10() + geom_label(x=11.1, y=25, label = "Japan") + facet_wrap(~region) + theme(legend.position = "none") + labs(title="Military Expenses in high income countries")df_military_gdp <- WDI(country = "all", indicator = c(military_gdp = "MS.MIL.XPND.GD.ZS"), extra=TRUE, cache=wdi_cache)
df_military_gdp %>% filter(country == "Japan", year==2021)df_military_gdp %>% drop_na(military_gdp) %>% filter(year==2021, income!="Aggregates") %>%
ggplot(aes(military_gdp, fill=income)) + geom_density(binwidth = 0.2, alpha=0.5) + geom_vline(xintercept = 2, col="red") + geom_vline(xintercept = 1, col="blue") + facet_wrap(~income)Warning: Ignoring unknown parameters: `binwidth`
他のデータで、同様のことをしてみましょう。
gdp = "NY.GDP.MKTP.CD" としましたが、GNI per
capita, Atlas method (current US$): NY.GNP.PCAP.CD
に変えてみましょう。df_gnppcap <- WDI(country = "all",
indicator = c(gnppcap = "NY.GNP.PCAP.CD"),
extra = TRUE)下のリンクを開き、右上の Code ボタンから、Download Rmd を選択すると、ダウンロードできますから、ダインロードしたものを、プロジェクト・フォールダーに移動またはコピーしてください。ダウンロードできないときは、Ctrl を押しながら、Download Rmd をクリックすると、Save As で保存できると思います。ブラウザーによって仕様が異なりますから、適切な方法を選んでください。
Windows でも、Mac でも提供されている、Google Chrome の場合には、Code ボタンから、ダンロードされるはずです。
RStudio Cloudは、誰でもオンラインでデータサイエンスを行い、共有し、教え、学ぶことができる、軽量でクラウドベースのソリューションです。月25時間の制限がありますが、内容を共有して、他のアカウントから利用することも可能です。
Posit Primers https://posit.cloud/learn/primers
R For Data Science, by H. Wickham: https://r4ds.had.co.nz
Bookdown: https://bookdown.org, Archive